package com.changgou.auth.controller;

import com.changgou.auth.service.AuthService;
import com.changgou.auth.util.AuthToken;
import com.changgou.auth.util.CookieUtil;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

//@RestController
@Controller
@RequestMapping("/oauth")
public class AuthController {

    @Autowired
    private AuthService authService;

    @Value("${auth.clientId}")
    private String clientId;

    @Value("${auth.clientSecret}")
    private String clientSecret;

    @Value("${auth.cookieDomain}")
    private String cookieDomain;

    @Value("${auth.cookieMaxAge}")
    private int cookieMaxAge;

    @RequestMapping(path = "/login")
    @ResponseBody
    public Result login(String username, String password, HttpServletResponse response) {
        //数据校验
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            throw new RuntimeException("用户名或密码为空");
        }
        try {
            //调用业务层方法进行认证
            AuthToken authToken = authService.login(username, password, clientId, clientSecret);
            //讲认证信息保存到cookie --->jti
            CookieUtil.addCookie(response, cookieDomain, "/", "uid", authToken.getJti(), cookieMaxAge, false);
            return new Result(true, StatusCode.OK, "登录成功", authToken.getJti());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, e.getMessage());
        }

    }

    //跳转到登录页面
    @RequestMapping("/toLogin")
    public String toLogin(@RequestParam(value = "from",required = false,defaultValue = "") String from, Model model) {
        model.addAttribute("from",from);
        return "login";
    }
}
